import { EventStreamContentType, fetchEventSource } from '@microsoft/fetch-event-source';
import { message } from 'antd';
import { useCallback, useEffect, useMemo ,useRef} from 'react';
import { getProcess_report, checkType, comment } from '@/client/api/request';
import i18n from '@/app/i18n';
/* import EventSource from 'event-source-polyfill'; */
type Props = {
  queryAgentURL?: string;
};

type ChatParams = {
  chatId: string;
  data?: Record<string, any>;
  onMessage: (message: string) => void;
  onClose?: () => void;
  onDone?: () => void;
  onError?: (content: string, error?: Error) => void;
};

const useChat = ({ queryAgentURL = '/api/v1/chat/completions' }: Props) => {
  let ctrl1 = useRef<AbortController>();
  let ctrl2 = useRef<AbortController>();
  let ctrl3 = useRef<AbortController>();
  let ctrl4 = useRef<AbortController>();
  let tempMessage = '';
  const chat = useCallback(
    async ({ data, chatId, onMessage, onClose, onDone, onError }: ChatParams) => {
      ctrl1.current = new AbortController();
      ctrl2.current = new AbortController();
      ctrl3.current = new AbortController();
      ctrl4.current = new AbortController();
      checkType({ content: data?.user_input },{
        signal: ctrl3.current.signal,
      }).then(async (res) => {
        const checkTypeRes = res.data.data;
        tempMessage = '';
        if (checkTypeRes == 'chart') {
          if (!data?.user_input && !data?.doc_id) {
            message.warning(i18n.t('NoContextTip'));
            return;
          }

          const parmas = {
            ...data,
            conv_uid: chatId,
          };
          if (!parmas.conv_uid) {
            message.error('conv_uid 不存在，请刷新后重试');
            return;
          }

          try {
            await fetchEventSource(`${process.env.API_BASE_URL ?? ''}${queryAgentURL}`, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify(parmas),
              signal: ctrl2.current.signal,
              openWhenHidden: true,
              async onopen(response) {
                if (response.ok && response.headers.get('content-type') === EventStreamContentType) {
                  return;
                }
              },
              onclose() {
                //ctrl2.current.abort();
                //onClose?.();
              },
              onerror(err) {
                throw new Error(err);
              },
              onmessage: (event) => {
                const message = event.data?.replaceAll('\\n', '\n');
                /* const message ='www' */
                console.log();
                if (message === '[DONE]') {
                  onDone?.();
                } else if (message?.startsWith('[ERROR]')) {
                  onError?.(message?.replace('[ERROR]', ''));
                } else {
                  if (message.includes('data&quot;:')) {
                    console.log(message);
                    const temp = message.split('data&quot;:')[1] || '';
                    const user_content = temp.length > 0 ? temp.split(`}" />`)[0] : '';
                    const data = {
                      user_content,
                    };
                    // debugger;
                    getProcess_report(JSON.stringify(data),
                    {
                      headers: {
                        'Content-Type': 'application/json',
                      },
                      signal: ctrl4.current!.signal,
                    }
                    ).then((res) => {
                      console.log(res);
                      if (res.status == 200) {
                        /*  '' */
                        /* const regex = /<chart-view\s*\/>/;
                        const match = message.match(regex); */
                        const iframeDom = document.getElementById('numberPerson') as HTMLIFrameElement;
                        iframeDom?.contentWindow?.postMessage(
                          { text: res.data?.choices[0].message.content, interactType: 'broadcast' },
                          'https://ai.it.10086.cn:9060/digitalhuman/digitalhuman-cmit-h5/2D-h5/bigScreen',
                        );
                        // debugger;
                        if (message.includes('<chart-view')) {
                          let chart = '<chart-view' + message.split('<chart-view')[1];
                          onMessage?.(res.data?.choices[0].message.content + chart);
                        } else {
                          onMessage?.(message);
                        }
                        onClose?.();
                      } else {
                        onMessage?.(message);
                        onClose?.();
                      }
                    }).catch((error) => {
                      onClose?.();
                      console.log(error)
                    });
                  } else {
                    onMessage?.(message);
                  }
                }
              },
            });
          } catch (err) {
            ctrl2.current.abort();
            onClose?.();
            onError?.('Sorry, We meet some error, please try agin later.', err as Error);
          }
        } else if (checkTypeRes == 'common') {
          const commentData = {
            userId: 1,
            messages: [
              {
                role: 'user',
                content: data?.user_input,
              },
            ],
            code: 1,
          };
          try {
            await fetchEventSource(`https://dev-tianshu.chaoshanhomeland.net:9930/dubhe-ai/ai/message`, {
              method: 'POST',
              headers: {
                'Content-Type': 'application/json',
              },
              body: JSON.stringify(commentData),
              signal: ctrl1.current.signal,
              openWhenHidden: true,
              async onopen(response) {
                if (response.ok && response.headers.get('content-type') === EventStreamContentType) {
                  return;
                }
              },
              onclose() {
                ctrl1.current!.abort();
                onClose?.();
              },
              onerror(err) {
                throw new Error(err);
              },
              onmessage: (event) => {
                /* const message = event.data?.replaceAll('\\n', '\n'); */
                /* const message ='www' */
                const finishReason = JSON.parse(event.data).choices[0].finishReason;
                const finishContent = JSON.parse(event.data).choices[0].delta.content;
                
                //const iframeDom = document.getElementById('numberPerson') as HTMLIFrameElement;
                // iframeDom?.contentWindow?.postMessage(
                //       { text: finishContent, interactType: 'broadcast' },
                //       'https://ai.it.10086.cn:9060/digitalhuman/digitalhuman-cmit-h5/2D-h5/bigScreen',
                //     );
                onMessage?.(finishContent || '');
                tempMessage += finishContent || '';
                
                debugger;
                if (finishReason == 'stop') {
                  /* onMessage?.(finishContent || ''); */
                  const iframeDom = document.getElementById('numberPerson') as HTMLIFrameElement;
                  // debugger;
                  iframeDom?.contentWindow?.postMessage(
                    { text: tempMessage, interactType: 'broadcast' },
                    'https://ai.it.10086.cn:9060/digitalhuman/digitalhuman-cmit-h5/2D-h5/bigScreen',
                  );
                  //onMessage?.(tempMessage || '');
                  tempMessage = '';
                } else {
                }

                // console.log(event);
                /* if (message === '[DONE]') {

                } else if (message?.startsWith('[ERROR]')) {
                  onError?.(message?.replace('[ERROR]', ''));
                } else {
                } */
              },
            });
          } catch (err) {
            debugger
            ctrl1.current.abort();
            onError?.('Sorry, We meet some error, please try agin later.', err as Error);
          }

          /* console.log(checkTypeRes.data);
          const commentRes = await comment(commentData);
          let finishReason = true; */

          /* while (finishReason) {} */
          /*  let dataCommentRes = JSON.parse(commentRes); */
        }
          console.log('res',res)
      }).catch((error)=>{
        console.log(error)
      });
      
    },
    [queryAgentURL],
  );
  // 取消请求
  const cancelRequest = ()=>{
    if(ctrl1.current&&ctrl2.current&&ctrl3.current&&ctrl4.current){
      console.log('取消请求')
      console.log('ctrl1',ctrl1)
      console.log('ctrl2',ctrl2)
      try{
        ctrl1.current.abort();
        ctrl2.current.abort();
        ctrl3.current.abort();
        ctrl4.current.abort();
      }catch(error){
        console.log(error)
      }
      
    }
   
  }
  useEffect(() => {
    return () => {
      cancelRequest()
    };
  }, []);

  return {cancelRequest,chat};
};

export default useChat;